/*
 * 人人信用管理有限公司版权所有.
 * 
 * @Description:
 * 
 * @author: liyuliang
 * 
 * @date: 20 Apr 2017 10:44:16 am
 * 
 * 注意：本内容仅限于人人信用管理有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */

package com.rrx360.common.context.spring;

import java.io.IOException;
import java.net.URL;
import java.util.Set;
import java.util.TreeSet;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.Resource;

public class IgnoringDuplicateFilesBeanDefinitionReader extends XmlBeanDefinitionReader {

  private Set<String> loadedLocations;

  public Set<String> getLoadedLocations() {
    if (loadedLocations == null) {
      loadedLocations = new TreeSet<String>();
    }
    return loadedLocations;

  }

  public IgnoringDuplicateFilesBeanDefinitionReader(DefaultListableBeanFactory beanFactory) {
    super(beanFactory);
  }

  public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
    String location = getUrl(resource).toString();
    if (getLoadedLocations().contains(location)) {
      logger.warn("Ignoring already loaded context [" + resource.getFilename() + "] - " + location);
      return 0;
    } else {
      getLoadedLocations().add(location);
      return super.loadBeanDefinitions(resource);
    }
  }

  private URL getUrl(Resource resource) {
    try {
      return resource.getURL();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

}
